﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Nirvana
{
    public class RepeatedTimer : IDisposable
    {
        private static Logger logger = LogSystem.GetLogger("RepeatedTimer");
        private LinkedListNode<Action> eventlist;
        private float mSpeed=1f;
        public float Speed
        {
            get { return mSpeed; }
            set { mSpeed = value; }
        }
        private float mDelay;
        public  float DelayTime { get { return this.mDelay; } }

        private float mRepeatTime;
        public float RepeatTime { get { return mRepeatTime; } }

        private bool unscaledDeltaTime = false;
        private Action onCompleteEvent;

        public  static RepeatedTimer Repeat(float interval,Action cb){
            var timer = new RepeatedTimer();
            timer.mDelay = interval;
            timer.mRepeatTime = interval;
            timer.unscaledDeltaTime = false;
            timer.onCompleteEvent = cb;
            timer.RegisterEvent();
            return timer;
        }
        public static RepeatedTimer Repeat(float delay,float interval, Action cb)
        {
            var timer = new RepeatedTimer();
            timer.mDelay = delay;
            timer.mRepeatTime = interval;
            timer.unscaledDeltaTime = false;
            timer.onCompleteEvent = cb;
            timer.RegisterEvent();
            return timer;
        }

        private void RegisterEvent()
        {
            this.eventlist = Scheduler.AddFrameListener(this.OnUpdate);
        }

        private void OnUpdate()
        {
            if (unscaledDeltaTime)
            {
                this.mDelay -= Time.unscaledDeltaTime * this.mSpeed;
            }
            else
            {
                this.mDelay -= Time.deltaTime * this.mSpeed;
            }

            if(this.mDelay <= 0)
            {
                try
                {
                    this.onCompleteEvent();
                }catch(Exception ex)
                {
                    logger.LogError(ex);
                }
                finally
                {
                    this.mDelay = mRepeatTime;
                }
            }
        }


        public void Dispose()
        {
            Scheduler.RemoveFrameListener(this.eventlist);
            this.eventlist = null;
        }
    }

}
